﻿using Helpers.Enums;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Helpers.Attributes
{
    public class ResponseCacheAttribute : IAsyncActionFilter
    {
        private readonly ApiCacheOptions _responseCacheOptions;

        public ResponseCacheAttribute(ApiCacheOptions responseCacheOptions)
        {
            _responseCacheOptions = responseCacheOptions;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var request = context.HttpContext.Request;
            var path = request.Path.Value.TrimEnd('/') + "/";
            if (!request.Query.TryGetValue("cacheKey", out var key) && !request.Headers.TryGetValue("x-cache-key", out key))
            {
                key = string.Join(",", request.Query
                    .Select(x => (x.Key.ToLower(), x.Value))
                    .Where(x => x.Item1 != "cachekey" && x.Item1 != "cachettl" && x.Value.Any(x => !string.IsNullOrWhiteSpace(x)))
                    .OrderBy(x => x.Item1)
                    .Select(x => $"{x.Value}"));
            }
            if (!request.Query.TryGetValue("cacheTtl", out var ttl) && !request.Headers.TryGetValue("x-cache-ttl", out ttl))
            {
                ttl = "1d";
            }
            if (!string.IsNullOrWhiteSpace(ttl) && !string.IsNullOrWhiteSpace(key))
            {
                var cacheValue = await WeedFsHttpClient.Instance.GetAsync(path + key).ConfigureAwait(false);
                if (!string.IsNullOrEmpty(cacheValue))
                {
                    var contentResult = new ContentResult
                    {
                        StatusCode = 222,
                        Content = cacheValue
                    };
                    context.Result = contentResult;
                    return;
                }
            }

            var fdf = await next();
        }
    }
}
